<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
			<view class="nav-content">
				<view class="nav-left" @click="goBack">
					<u-icon name="arrow-left" color="#333" size="18"></u-icon>
				</view>
				<view class="nav-title">{{ operationType === 'pay' ? '订单支付' : '订单信息' }}</view>
				<view class="nav-right"></view>
			</view>
		</view>
		
		<!-- 主内容区域 -->
		<view class="main-content" :style="{paddingTop: (statusBarHeight + 44) + 'px'}">
			<!-- 收货地址选择 -->
		<view class="address-section" @click="selectAddress">
				<view class="address-content" v-if="!selectedAddress">
					<u-icon name="map" color="#4CAF50" size="20"></u-icon>
				<text class="address-text">{{ operationType === 'pay' ? '订单已确认收货地址' : '请选择收货地址' }}</text>
				</view>
				<view class="selected-address-content" v-else>
					<view class="address-header">
						<u-icon name="map" color="#4CAF50" size="20"></u-icon>
						<text class="address-label">收货地址</text>
					</view>
					<view class="address-info">
						<view class="user-info">
							<text class="name">{{selectedAddress.addressName}}</text>
							<text class="phone">{{selectedAddress.addressPhone}}</text>
						</view>
						<view class="address-detail">{{selectedAddress.addressInfo}} {{selectedAddress.addressCommunity}}</view>
					</view>
				</view>
			<u-icon name="arrow-right" color="#999" size="16"></u-icon>
			</view>
			
			<!-- 商品信息 -->
			<view class="product-section">
				<view class="product-item">
					<image class="product-image" :src="productInfo.image" mode="aspectFill"></image>
					<view class="product-details">
						<view class="product-title">{{productInfo.title}}</view>
						<view class="product-price-row">
							<text class="product-price">售价:{{productInfo.price}}元</text>
							<text class="product-quantity">x {{quantity}}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 优惠券选择 -->
			<view class="coupon-section" @click="selectCoupon">
				<view class="coupon-content">
					<u-icon name="coupon-fill" color="rgb(230,104,89)" size="20"></u-icon>
					<text class="coupon-text">优惠券</text>
				</view>
				<view class="coupon-right">
					<text class="coupon-status">暂无优惠券</text>
					<u-icon name="arrow-right" color="#999" size="16"></u-icon>
				</view>
			</view>
			
			<!-- 价格明细 -->
			<view class="price-section">
				<view class="price-item">
					<text class="price-label">商品金额</text>
					<text class="price-value">¥ {{totalAmount}}</text>
				</view>
				<view class="price-item">
					<text class="price-label">会员折扣</text>
					<text class="price-discount">- ¥ {{memberDiscount}}</text>
				</view>
				<view class="price-item">
					<text class="price-label">总优惠金额</text>
					<text class="price-discount">- ¥ {{totalDiscount}}</text>
				</view>
			</view>
		</view>
		
		<!-- 底部支付栏 -->
		<view class="bottom-pay">
			<view class="pay-info">
				<text class="pay-label">实付款</text>
				<text class="pay-amount">¥ {{finalAmount}}</text>
			</view>
			<view class="pay-btn" @click="submitOrder">
				{{ operationType === 'pay' ? '立即支付' : '提交订单' }}
			</view>
		</view>
		
		<!-- 支付方式选择弹出层 -->
		<u-popup :show="paymentVisible" mode="bottom" :round="20" @close="closePayment" :safe-area-inset-bottom="true">
			<view class="payment-popup">
				<view class="payment-header">
					<view class="payment-title">支付金额</view>
					<u-icon name="close" @click="closePayment" size="20" color="#999"></u-icon>
				</view>
				<view class="payment-amount">¥ {{finalAmount}}</view>
				
				<view class="payment-methods">
					<!-- 微信支付 -->
					<view 
						class="payment-item" 
						:class="{ active: selectedPaymentType === 'wechat' }"
						@click="selectPaymentType('wechat')"
					>
						<view class="payment-info">
							<view class="payment-icon wechat-icon">
								<text>微</text>
							</view>
							<view class="payment-details">
								<view class="payment-name">微信支付</view>
								<view class="payment-desc">推荐使用微信支付</view>
							</view>
						</view>
						<view class="payment-radio">
							<view 
								class="radio-icon"
								:class="{ selected: selectedPaymentType === 'wechat' }"
							>
								<view v-if="selectedPaymentType === 'wechat'" class="radio-dot"></view>
							</view>
						</view>
					</view>
					
					<!-- 余额支付 -->
					<view 
						class="payment-item" 
						:class="{ active: selectedPaymentType === 'balance' }"
						@click="selectPaymentType('balance')"
					>
						<view class="payment-info">
							<view class="payment-icon balance-icon">
								<text>¥</text>
							</view>
							<view class="payment-details">
								<view class="payment-name">余额支付</view>
								<view class="payment-desc">可用余额 ¥{{userBalance}}</view>
							</view>
						</view>
						<view class="payment-radio">
							<view 
								class="radio-icon"
								:class="{ selected: selectedPaymentType === 'balance' }"
							>
								<view v-if="selectedPaymentType === 'balance'" class="radio-dot"></view>
							</view>
						</view>
					</view>
					
					<!-- 支付密码输入框（仅在选择余额支付时显示） -->
					<view v-if="selectedPaymentType === 'balance'" class="password-input-section">
						<view class="password-label">请输入支付密码</view>
						<u--input
							v-model="paymentPassword"
							type="number"
							placeholder="请输入6位支付密码"
							:maxlength="6"
							:border="'surround'"
							:customStyle="{ 
								backgroundColor: '#f8f8f8',
								borderRadius: '10rpx',
								padding: '20rpx',
								fontSize: '32rpx'
							}"
							password
							@input="onPasswordInput"
						></u--input>
					</view>
				</view>
				
				<view class="payment-footer">
					<view class="confirm-payment-btn" @click="confirmPayment">
						确认支付
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import request from '@/util/request.js'
	
	export default {
		data() {
			return {
				statusBarHeight: 0,
				// 商品信息
				productInfo: {
					id: null,
					title: "",
					price: 0,
					image: ""
				},
				// 购买数量
				quantity: 1,
				// 认养周期天数
				periodDays: 0,
				// 会员折扣
				memberDiscount: 0.00,
				// 总优惠金额
				totalDiscount: 0.00,
				// 选中的地址信息
				selectedAddress: null,
				// 支付弹出层
				paymentVisible: false,
				// 用户余额
				userBalance: 0.00,
				// 选中的支付方式
				selectedPaymentType: 'wechat', // wechat: 微信支付, balance: 余额支付
				// 预生成的订单号
				orderNum: '',
				// 支付密码
				paymentPassword: '',
				// 操作类型：create-创建订单, pay-付款
				operationType: 'create',
				// 现有订单ID（付款时使用）
				existingOrderId: null
			}
		},
		computed: {
			// 商品总金额
			totalAmount() {
				return (this.productInfo.price * this.quantity).toFixed(2);
			},
			// 实付金额
			finalAmount() {
				const amount = this.productInfo.price * this.quantity - this.memberDiscount - this.totalDiscount;
				return Math.max(0, amount).toFixed(2);
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 选择收货地址
			selectAddress() {
				console.log('点击选择收货地址');
				uni.navigateTo({
					url: '/pages/farm/selectAddress',
					fail: (err) => {
						console.error('页面跳转失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 设置选中的地址（由地址选择页面调用）
			setSelectedAddress(address) {
				this.selectedAddress = address;
				console.log('选中的地址:', address);
			},
			
			// 选择优惠券
			selectCoupon() {
				uni.showToast({
					title: '还想要优惠券？',
					icon: 'none'
				});
			},
			
			// 提交订单
			async submitOrder() {
				if (this.operationType === 'pay') {
					// 付款操作：直接显示支付选择弹出层
					this.paymentVisible = true;
					return;
				}
				
				// 创建新订单操作
				// 先检查是否选择了收货地址
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请先选择收货地址',
						icon: 'none'
					});
					return;
				}
				
				// 检查用户信息
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || !userInfo.userId) {
					uni.showToast({
						title: '用户信息获取失败，请重新登录',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({
						title: '创建订单中...'
					});
					
					// 使用预生成的订单号
					const orderNum = this.orderNum;
					
					// 准备订单数据
					const orderData = {
						order_num: orderNum,
						user_id: userInfo.userId,
						order_type: '认养',
						related_id: this.productInfo.id,
						order_amount: parseFloat(this.finalAmount),
						least_time: this.periodDays,
						order_address_id: this.selectedAddress.addressId,
						order_quantity: this.quantity
					};
					
					console.log('准备创建订单，数据:', orderData);
					
					// 调用后端API创建订单
					const response = await request({
						url: '/adopt-service/order/create',
						method: 'POST',
						data: orderData
					});
					
					uni.hideLoading();
					
					if (response.success) {
						console.log('订单创建成功:', response);
						// 显示支付方式选择弹出层
						this.paymentVisible = true;
					} else {
						uni.showToast({
							title: response.message || '创建订单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('创建订单失败:', error);
					uni.showToast({
						title: '创建订单失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			
			// 关闭支付弹出层
			closePayment() {
				this.paymentVisible = false;
				// 清空支付密码
				this.paymentPassword = '';
			},
			
			// 选择支付方式
			selectPaymentType(type) {
				this.selectedPaymentType = type;
			},
			
			// 确认支付
			confirmPayment() {
				if (this.selectedPaymentType === 'balance') {
					// 余额支付
					this.payWithBalance();
				} else {
					// 微信支付
					this.payWithWechat();
				}
			},
			
			// 微信支付
			payWithWechat() {
				uni.showToast({
					title: '调用微信支付中...',
					icon: 'loading'
				});
				
				// 这里调用微信支付接口
				setTimeout(() => {
					uni.hideToast();
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					});
					this.paymentVisible = false;
					// 跳转到支付成功页面或订单详情页面
				}, 2000);
			},
			
			// 余额支付
			async payWithBalance() {
				// 先验证支付密码
				if (!this.paymentPassword || this.paymentPassword.length !== 6) {
					uni.showToast({
						title: '请输入6位支付密码',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({
						title: '余额支付中...'
					});
					
					// 获取用户信息
					const userInfo = uni.getStorageSync('userInfo');
					if (!userInfo || !userInfo.userId) {
						uni.hideLoading();
						uni.showToast({
							title: '用户信息获取失败，请重新登录',
							icon: 'none'
						});
						return;
					}
					
					let paymentData;
					if (this.operationType === 'pay') {
						// 付款操作：使用现有订单ID
						paymentData = {
							user_id: userInfo.userId,
							order_id: this.existingOrderId,
							order_amount: parseFloat(this.finalAmount),
							payment_password: this.paymentPassword
						};
					} else {
						// 新建订单操作：使用订单号
						paymentData = {
							user_id: userInfo.userId,
							order_num: this.orderNum,
							order_amount: parseFloat(this.finalAmount),
							payment_password: this.paymentPassword
						};
					}
					
					console.log('余额支付数据:', paymentData);
					
					// 调用后端余额支付接口
					const response = await request({
						url: '/adopt-service/order/balancePay',
						method: 'POST',
						data: paymentData
					});
					
					uni.hideLoading();
					
					if (response.code === 200) {
						uni.showToast({
							title: '支付成功',
							icon: 'success'
						});
						this.paymentVisible = false;
						// 清空支付密码
						this.paymentPassword = '';
						// 刷新用户余额
						this.getUserBalance();
						// 跳转到支付成功页面或订单详情页面
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: response.message || '支付失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('余额支付失败:', error);
					uni.showToast({
						title: '支付失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			
			// 获取用户余额
			async getUserBalance() {
				try {
					const userInfo = uni.getStorageSync('userInfo');
					console.log('获取到的用户信息:', userInfo);
					
					if (!userInfo || !userInfo.userId) {
						console.log('未找到用户信息，无法获取余额');
						return;
					}
					
					console.log('准备调用API获取余额，userId:', userInfo.userId);
					
					// 调用API获取用户余额
					const response = await request({
						url: `/user-service/user/balance?userId=${userInfo.userId}`,
						method: 'GET'
					});
					
					console.log('API返回的完整响应:', response);
					
					if (response.success && response.data) {
						// 设置用户余额，保留两位小数
						console.log('原始余额值:', response.data.balance);
						console.log('余额类型:', typeof response.data.balance);
						
						this.userBalance = response.data.balance ? response.data.balance.toFixed(2) : '0.00';
						console.log('设置后的用户余额:', this.userBalance);
					} else {
						console.error('获取用户余额失败:', response.message);
						this.userBalance = '0.00';
					}
				} catch (error) {
					console.error('获取用户余额失败:', error);
					// 出现错误时设置默认值
					this.userBalance = '0.00';
				}
			},
			
			// 处理支付密码输入
			onPasswordInput(value) {
				this.paymentPassword = value;
			}
		},
		onLoad(options) {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			
			// 检查是否是付款操作
			const isPayment = options.type === 'pay';
			
			if (isPayment && options.orderId) {
				// 付款操作：使用现有订单号
				this.orderNum = ''; // 付款时不需要生成新订单号
				this.existingOrderId = options.orderId; // 保存现有订单ID
				console.log('付款操作，订单ID:', options.orderId);
			} else {
				// 新建订单：生成订单号
			this.orderNum = 'ADOPT' + Date.now();
				console.log('新建订单，生成订单号:', this.orderNum);
			}
			
			// 接收传递的参数
			if (options.id) {
				this.productInfo.id = options.id;
			}
			if (options.title) {
				this.productInfo.title = decodeURIComponent(options.title);
			}
			if (options.price) {
				this.productInfo.price = parseFloat(options.price);
			}
			if (options.image) {
				this.productInfo.image = decodeURIComponent(options.image);
			}
			if (options.quantity) {
				this.quantity = parseInt(options.quantity);
			}
			if (options.periodDays) {
				this.periodDays = parseInt(options.periodDays);
			}
			
			// 保存操作类型
			this.operationType = isPayment ? 'pay' : 'create';
			
			console.log('订单信息页面参数:', {
				operationType: this.operationType,
				existingOrderId: this.existingOrderId,
				id: this.productInfo.id,
				title: this.productInfo.title,
				price: this.productInfo.price,
				image: this.productInfo.image,
				quantity: this.quantity,
				periodDays: this.periodDays,
				orderNum: this.orderNum
			});
			
			// 获取用户余额
			console.log('开始调用getUserBalance方法');
			this.getUserBalance();
		}
	}
</script>

<style scoped>
	/* 通用样式 */
	.container {
	  background-color: #f5f5f5;
	  min-height: 100vh;
	  padding-bottom: 120rpx;
	  box-sizing: border-box;
	}
	
	/* 自定义导航栏 */
	.nav-bar {
	  background-color: #ffffff;
	  border-bottom: 1rpx solid #f0f0f0;
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  z-index: 1000;
	}
	
	.status-bar {
	  width: 100%;
	  height: var(--status-bar-height);
	  background-color: #ffffff;
	}
	
	.nav-content {
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	  height: 88rpx;
	  padding: 0 30rpx;
	}
	
	.nav-left, .nav-right {
	  width: 60rpx;
	  height: 60rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  flex-shrink: 0;
	}
	
	.nav-title {
	  font-size: 32rpx;
	  font-weight: bold;
	  color: #333;
	  text-align: center;
	  flex: 1;
	}
	
	/* 主内容区域 */
	.main-content {
	  /* padding-top 通过内联样式动态设置，包含状态栏高度 */
	}
	
	/* 收货地址 */
	.address-section {
	  background-color: #ffffff;
	  padding: 30rpx;
	  margin-bottom: 20rpx;
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	}
	
	.address-icon {
	  width: 40rpx;
	  height: 40rpx;
	  margin-right: 20rpx;
	}
	
	.address-content {
	  display: flex;
	  align-items: center;
	  flex: 1;
	}
	
	.address-text {
	  font-size: 28rpx;
	  color: #333;
	  margin-left: 15rpx;
	}
	
	.selected-address-content {
	  flex: 1;
	}
	
	.address-header {
	  display: flex;
	  align-items: center;
	  margin-bottom: 15rpx;
	}
	
	.address-label {
	  font-size: 28rpx;
	  color: #333;
	  font-weight: 500;
	  margin-left: 15rpx;
	}
	
	.address-info {
	  padding-left: 35rpx;
	}
	
	.user-info {
	  display: flex;
	  align-items: center;
	  margin-bottom: 8rpx;
	}
	
	.user-info .name {
	  font-size: 28rpx;
	  color: #333;
	  font-weight: 500;
	  margin-right: 20rpx;
	}
	
	.user-info .phone {
	  font-size: 26rpx;
	  color: #666;
	}
	
	.address-detail {
	  font-size: 26rpx;
	  color: #666;
	  line-height: 1.4;
	}
	
	/* 商品信息 */
	.product-section {
	  background-color: #ffffff;
	  padding: 30rpx;
	  margin-bottom: 20rpx;
	}
	
	.product-item {
	  display: flex;
	  margin-bottom: 30rpx;
	}
	
	.product-item:last-child {
	  margin-bottom: 0;
	}
	
	.product-image {
	  width: 120rpx;
	  height: 120rpx;
	  border-radius: 12rpx;
	  margin-right: 20rpx;
	  flex-shrink: 0;
	}
	
	.product-details {
	  flex: 1;
	}
	
	.product-title {
	  font-size: 28rpx;
	  color: #333;
	  margin-bottom: 15rpx;
	  font-weight: 500;
	  display: -webkit-box;
	  -webkit-box-orient: vertical;
	  -webkit-line-clamp: 2;
	  overflow: hidden;
	}
	
	.product-price-row {
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	}
	
	.product-price {
	  font-size: 26rpx;
	  color: #FF5722;
	  font-weight: bold;
	}
	
	.product-quantity {
	  font-size: 26rpx;
	  color: #666;
	}
	
	/* 优惠券 */
	.coupon-section {
	  background-color: #ffffff;
	  padding: 30rpx;
	  margin-bottom: 20rpx;
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	}
	
	.coupon-content {
	  display: flex;
	  align-items: center;
	}
	
	.coupon-text {
	  font-size: 28rpx;
	  color: #333;
	  margin-left: 15rpx;
	}
	
	.coupon-right {
	  display: flex;
	  align-items: center;
	}
	
	.coupon-status {
	  font-size: 26rpx;
	  color: #999;
	  margin-right: 10rpx;
	}
	
	/* 价格明细 */
	.price-section {
	  background-color: #ffffff;
	  padding: 30rpx;
	  margin-bottom: 20rpx;
	}
	
	.price-item {
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	  margin-bottom: 25rpx;
	}
	
	.price-item:last-child {
	  margin-bottom: 0;
	}
	
	.price-label {
	  font-size: 28rpx;
	  color: #333;
	}
	
	.price-value {
	  font-size: 28rpx;
	  color: #333;
	  font-weight: 500;
	}
	
	.price-discount {
	  font-size: 28rpx;
	  color: #FF5722;
	  font-weight: 500;
	}
	
	/* 底部支付栏 */
	.bottom-pay {
	  position: fixed;
	  bottom: 0;
	  left: 0;
	  right: 0;
	  height: 120rpx;
	  background-color: #ffffff;
	  border-top: 1rpx solid #f0f0f0;
	  display: flex;
	  align-items: center;
	  padding: 0 30rpx;
	  z-index: 1000;
	}
	
	.pay-info {
	  flex: 1;
	}
	
	.pay-amount {
	  font-size: 36rpx;
	  color: #FF5722;
	  font-weight: bold;
	}
	
	.pay-btn {
	  background-color: #4CAF50;
	  color: #ffffff;
	  font-size: 32rpx;
	  font-weight: bold;
	  padding: 20rpx 60rpx;
	  border-radius: 40rpx;
	}
	
	/* 支付弹窗 */
	.payment-popup {
	  padding: 30rpx;
	}
	
	.payment-title {
	  font-size: 32rpx;
	  font-weight: bold;
	  color: #333;
	  text-align: center;
	  margin-bottom: 30rpx;
	}
	
	.payment-amount {
	  font-size: 48rpx;
	  color: #333;
	  font-weight: bold;
	  text-align: center;
	  margin-bottom: 40rpx;
	}
	
	.payment-item {
	  display: flex;
	  align-items: center;
	  padding: 30rpx;
	  border: 1rpx solid #f0f0f0;
	  border-radius: 10rpx;
	  margin-bottom: 20rpx;
	}
	
	.payment-item.active {
	  border-color: #4CAF50;
	}
	
	.payment-icon {
	  width: 50rpx;
	  height: 50rpx;
	  margin-right: 20rpx;
	  border-radius: 8rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  color: #fff;
	  font-size: 24rpx;
	}
	
	.payment-name {
	  font-size: 30rpx;
	  color: #333;
	  font-weight: 500;
	}
	
	.payment-desc {
	  font-size: 24rpx;
	  color: #666;
	}
	
	.radio-icon {
	  width: 40rpx;
	  height: 40rpx;
	  border: 2rpx solid #ccc;
	  border-radius: 50%;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	.radio-icon.selected {
	  border-color: #4CAF50;
	}
	
	.radio-icon.selected .radio-dot {
	  width: 20rpx;
	  height: 20rpx;
	  border-radius: 50%;
	  background-color: #4CAF50;
	}
	
	.confirm-payment-btn {
	  background-color: #4CAF50;
	  color: #fff;
	  font-size: 32rpx;
	  font-weight: bold;
	  padding: 25rpx;
	  border-radius: 50rpx;
	  text-align: center;
	  margin-top: 40rpx;
	}
</style> 